package com.katze.boot.common.config.actuator.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@WebEndpoint(id = "logger")
public class LoggerEndpoint {

    private static final Logger log = LoggerFactory.getLogger(LoggerEndpoint.class);

    private final File externalFile;

    public LoggerEndpoint(File externalFile) {
        this.externalFile = externalFile;
    }

//    @ReadOperation(produces = {"text/plain; charset=UTF-8"})
    public Resource logger() {
        Resource resource = this.getLogFileResource();
        return resource != null && resource.isReadable() ? resource : null;
    }

    @ReadOperation
    public List<String> logger(Integer lines) {
        Resource resource = this.getLogFileResource();
        if (resource == null || !resource.isReadable()) {
            return null;
        }
        List<String> content = new ArrayList<>();
        String encoding = System.getProperty("file.encoding", "UTF-8");
        try (InputStream stream = resource.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(stream, encoding))){
            in.lines().forEach(line-> {
                if (content.size() >= lines) {
                    content.removeFirst();
                }
                content.add(line);
            });
        } catch (IOException e) {
            log.error("load {} exception", resource.getFilename(), e);
        }
        return content;
    }

    private FileSystemResource getLogFileResource() {
        if (this.externalFile != null) {
            return new FileSystemResource(this.externalFile);
        } else {
            log.warn("Missing 'management.endpoint.logfile.external-file' properties");
            return null;
        }
    }
}
